import {message, Button, Table, Typography, Input, DatePicker, Select, Skeleton, notification} from 'antd'
import React, { useState, useRef, useEffect} from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import { connect } from 'umi'
import { getFundsRecordReportList } from './service'
import { getCompanyListAuth } from '../../service'
import moment from 'moment';

const { Text } = Typography;
const {Option} = Select;

const TableList = () => {
  const actionRef = useRef();
  const formRef = useRef();
  const [tableData, setTableData] = useState([]);
  const [contractData,setContractData] = useState(null);

  useEffect(() => {
    getCompanyListAuth().then(res => {
      if(res.flag){
        res && setContractData(res.data)
      }else{
        notification.error({
          message: `请求错误 ${res.status}`,
          description: res.error,
        });
      }
    });
  },[]);

  useEffect((res) => {
  },[contractData]);

  const columns = [
    {
      title: '序号',
      fixed: 'left',
      width: '40px',
      align: 'center',
      dataIndex: 'promotionId',
      render:(text,record,index)=>`${index+1}`,
      search:false,
    },
    {
      title: '姓名',
      width: '70px',
      align: 'center',
      dataIndex: 'name',
    },
    {
      title: '参保地',
      width: '140px',
      align: 'center',
      dataIndex: 'cityName',
      search:false,
    },
    {
      title: '参保单位',
      align: 'center',
      dataIndex: 'unitName',
      renderFormItem: (item, props) => {
        return <Select placeholder="请选择参保单位" showSearch filterOption={(input, option) =>
          option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} allowClear>
          { contractData?.length>0 ? contractData.map((item, index) => {
            return (
              <Option value={item.name} key={index} lable={item}>
                {item.name}
              </Option>
            )
          }) : ''}
        </Select>;
      },
    },
    {
      title: '公积金',
      children: [
        {
          title: '基数',
          dataIndex: 'reservedFundsBase',
          search:false,
        },
        {
          title: '个人',
          children: [
            {
              title: '缴纳',
              dataIndex: 'reservedFundsPerson',
              search:false,
            },
            {
              title: '比例',
              dataIndex: 'reservedFundsPersonRate',
              search:false,
            },
          ]
        },
        {
          title: '公司',
          children: [
            {
              title: '缴纳',
              dataIndex: 'reservedFundsOrg',
              search:false,
            },
            {
              title: '比例',
              dataIndex: 'reservedFundsOrgRate',
              search:false,
            },
          ]
        }
      ]
    },
    {
      title: '补充公积金',
      children: [
        {
          title: '基数',
          dataIndex: 'offerFundsBase',
          search:false,
        },
        {
          title: '个人',
          children: [
            {
              title: '缴纳',
              dataIndex: 'offerFundsPerson',
              search:false,
            },
            {
              title: '比例',
              dataIndex: 'offerFundsPersonRate',
              search:false,
            },
          ]
        },
        {
          title: '公司',
          children: [
            {
              title: '缴纳',
              dataIndex: 'offerFundsOrg',
              search:false,
            },
            {
              title: '比例',
              dataIndex: 'offerFundsOrgRate',
              search:false,
            },
          ]
        }
      ]
    },
    {
      title: '缴费时间',
      dataIndex: 'operateTime',
      renderFormItem: (item, props) => {
        return <DatePicker {...props} defaultValue={moment(new Date())} picker="month" />;
      },
      render: (text) => {
        return text!=='-'?moment(text).format('YYYY-MM'):''
      }
    },
    {
      title: '查询整年',
      dataIndex: 'isAllYear',
      renderFormItem: (item, props) => {
        return <Select defaultValue={1}>
          <Option value={0}>是</Option>
          <Option value={1}>否</Option>
        </Select>;
      },
      hideInTable: true
    },
    {
      title: '合计',
      children: [
        {
          title: '个人',
          dataIndex: 'personCostTotal',
          search:false,
        },
        {
          title: '公司',
          dataIndex: 'orgCostTotal',
          search:false,
        },
      ]
    },
  ];

  const setTotalRow = () => {
    let sumObj = {
      reservedFundsPersonSum: 0,
      reservedFundsOrgSum: 0,
      offerFundsPersonSum: 0,
      offerFundsOrgSum: 0,
      personCostTotalSum: 0,
      orgCostTotalSum: 0,
    };
    tableData?.forEach(({reservedFundsPerson, reservedFundsOrg, offerFundsPerson,
                          offerFundsOrg, personCostTotal, orgCostTotal}) => {
      sumObj.reservedFundsPersonSum += reservedFundsPerson;
      sumObj.reservedFundsOrgSum += reservedFundsOrg;
      sumObj.offerFundsPersonSum += offerFundsPerson;
      sumObj.offerFundsOrgSum += offerFundsOrg;
      sumObj.personCostTotalSum += personCostTotal;
      sumObj.orgCostTotalSum += orgCostTotal;
    });

    return (
      <>
        <Table.Summary.Row >
          <Table.Summary.Cell colSpan={4} index={0} className='textCenter'>小计</Table.Summary.Cell>
          <Table.Summary.Cell />
          <Table.Summary.Cell>
            <Text>{sumObj.reservedFundsPersonSum}</Text>
          </Table.Summary.Cell>
          <Table.Summary.Cell />
          <Table.Summary.Cell>
            <Text>{sumObj.reservedFundsOrgSum}</Text>
          </Table.Summary.Cell>
          <Table.Summary.Cell />
          <Table.Summary.Cell />
          <Table.Summary.Cell>
            <Text>{sumObj.offerFundsPersonSum}</Text>
          </Table.Summary.Cell>
          <Table.Summary.Cell />
          <Table.Summary.Cell>
            <Text>{sumObj.offerFundsOrgSum}</Text>
          </Table.Summary.Cell>
          <Table.Summary.Cell />
          <Table.Summary.Cell index={39} />
          <Table.Summary.Cell index={40}>
            <Text>{sumObj.personCostTotalSum}</Text>
          </Table.Summary.Cell>
          <Table.Summary.Cell index={41}>
            <Text>{sumObj.orgCostTotalSum}</Text>
          </Table.Summary.Cell>
        </Table.Summary.Row>
      </>
    );
  };

  const exportExcel = () => {
    let searchData = formRef.current.getFieldsValue();
    let {operateTime, name, isAllYear, unitName} = searchData;
    window.open(`/hr-ssc/api/api-admin/export/exportFundRecordReport?operateTime=${moment(operateTime || new Date()).format('YYYY-MM-DD')}&name=${name || null}&unitName=${unitName || null}&isAllYear=${isAllYear===0 ? 0 : 1}`)
  };

  return (
    <PageHeaderWrapper>
      {
        contractData && <ProTable
          bordered
          actionRef={actionRef}
          formRef={formRef}
          rowKey="recordId"
          request={(params) => getFundsRecordReportList(params).then(res=>{
            setTableData(res.data);
            return res;
          })}
          columns={columns}
          toolBarRender={(action, { selectedRows }) => [
            <Button key='button' type="primary" onClick={() => exportExcel()}>导出</Button>,
          ]}
          summary={setTotalRow}
          pagination={{pageSizeOptions:['50', '100', '200', '500']}}
          search={{defaultCollapsed: false}}
        />
      }
    </PageHeaderWrapper>
  )
};

export default connect(({  }) => ({
}))(TableList)
